<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    :title="title"
    width="720"
    show-footer
    show-zoom
    resize
    @close="close"
    :z-index="2000"
  >
    <div class="flex justify-between uploadBox mb-4" v-if="handleType == 'export'">
      <VUpload :limit="limit" :validator="validator" type="file" @success="success">
        <el-button type="primary" link class="flex items-center">
          <svg-icon icon-class="Plus"></svg-icon> 上传文件
        </el-button>
      </VUpload>
    </div>
    <div class="flex justify-between pb-4" v-else>
      <div class="flex items-center flex-wrap">
        <div
          class="flex items-center mr-2"
          v-for="(item, index) in authentication_list"
          :key="index"
        >
          <svg-icon
            class="text-white"
            style="margin-top: -2px"
            :icon-class="item.isOwn ? 'state_finish_cover3' : 'state_fail_cover01'"
          ></svg-icon>
          {{ item.name }}
        </div>
      </div>
      <div
        class="w-20 text-blue-500"
        @click="downloadAll"
        v-if="authentication_list.length > 0"
      >
        全部下载
      </div>
    </div>
    <vxe-table
      ref="tableRef"
      show-overflow
      height="400"
      :data="form.certificate"
      @checkbox-change="checkboxChangeEvent"
      @checkbox-all="checkboxChangeEvent"
      :column-config="{ resizable: true }"
    >
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column field="type" title="证书类型" width="200">
        <template #default="{ row }">
          <template v-if="handleType == 'export'">
            <el-select
              v-model="row.certificate_type"
              clearable
              placeholder="请选择"
              class="w-full"
            >
              <el-option
                v-for="item in props.options['goods.GoodsSpu']?.[0].authenticationText"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
          <template v-else>{{ row.certificate_type_text }}</template>
        </template>
      </vxe-column>
      <vxe-column field="filename" title="证书文件"></vxe-column>
      <vxe-column field="purchase_price" title="操作" width="100">
        <template #default="{ row, rowIndex }">
          <el-link
            type="danger"
            :undefined="false"
            @click="handleRemove(rowIndex)"
            v-if="handleType == 'export'"
            >删除</el-link
          >
          <el-link type="primary" :undefined="false" @click="handleDownload(row)" v-else
            >下载</el-link
          >
        </template>
      </vxe-column>
    </vxe-table>
    <template #footer>
      <div class="flex justify-between items-center" v-if="handleType == 'export'">
        <div class="text-sm">
          已上传 <span class="text-blue-500">{{ form.certificate.length }}</span> 条
        </div>
        <div>
          <el-button @click="close">取消</el-button>
          <el-button type="primary" :loading="loading" @click="save()">保存</el-button>
        </div>
      </div>
      <div class="flex justify-center items-center" v-else>
        <div><el-button @click="close">关闭</el-button></div>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="CertificateInformation">
import { reactive, ref, toRefs } from "vue";
import VUpload from "@/components/VUpload/index.vue";
import { certificateImport, getCertificateList } from "../../api/index";
import { downloadFile, batchDownload } from "@/utils/downloadFile.js";

import { ElMessage, ElSelect } from "element-plus";
const visible = ref(false);
const loading = ref(false);
// const props = defineProps()
// const options = reactive(inject('options'))

const props = defineProps({
  options: {
    type: Object,
    default: {},
  },
});

const data = reactive({
  form: null,
  handleType: "",
  title: "",
  authentication_list: [],
  load: false,
});

const { form, handleType, title, authentication_list, load } = toRefs(data);

// 初始化
const getForm = () => {
  return {
    spu_ids: null,
    certificate: [],
  };
};

const statusMap = new Map([
  ["export", "证书导入"],
  ["info", "证书信息"],
]);

const open = async (type, spu_ids, authentication_text) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  title.value = statusMap.get(type);
  handleType.value = type;
  if (type == "info") {
    getCertificate(spu_ids, authentication_text);
  } else {
    form.value.spu_ids = spu_ids;
  }
  visible.value = true;
};

const success = (obj) => {
  form.value.certificate.push({
    filename: obj.filename,
    filepath: obj["data-show-file"],
    certificate_type: "",
    certificate_class: 1,
    remark: "",
  });
};
// 上传校验
const validator = (fileInfo) => {
  return (() => {})();
};
// 文件上传
const save = async () => {
  if (form.value.certificate.length == 0) {
    ElMessage.error("至少上传一项");
    return;
  }
  try {
    const res = await certificateImport(form.value);
    ElMessage.success(res.message);
    initForm();
    close();
  } catch (e) {
    throw Error(e);
  }
};
const handleRemove = (index) => {
  form.value.certificate.splice(index, 1);
};

const close = () => {
  visible.value = false;
};

const initForm = () => {
  form.value = getForm();
};

const downloadAll = () => {
  const list = form.value.certificate.map((i) => i.filepath);
  batchDownload(list, "证书文件");
};

const handleDownload = (row) => {
  downloadFile(row.filepath, row.filename);
};

const getCertificate = async (spu_id, authentication_text) => {
  try {
    const res = await getCertificateList({
      certificate_class: 2,
      spu_id,
    });
    form.value.certificate = res.data;
    let authentication = authentication_text
      .map((i) => {
        return {
          name: i,
        };
      })
      .map((i) => {
        if (res.data.findIndex((j) => i.name == j.certificate_type_text) != -1) {
          i.isOwn = true;
        }
        return i;
      });
    authentication_list.value = authentication;
  } catch (e) {
    throw Error(e);
  }
};

const filterType = (type) => {
  const item = props.options["goods.GoodsSpu"]?.[0].authenticationText.find(
    (i) => i.value == type
  );
  if (item == undefined) {
    return "--";
  } else {
    return item.label;
  }
};

onMounted(() => {
  initForm();
});
defineExpose({ open });
</script>
<style lang="scss" scoped>
.uploadBox {
  height: 52px;
  border-radius: 4px;
  border: 1px dashed #3366f1;
  justify-content: center;
  align-items: center;

  .v-upload {
    width: 100%;
    height: 100%;

    :deep(.el-upload) {
      width: 100%;
      height: 52px;
    }
  }
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.upload-file-uploader {
  display: flex;
  justify-content: center;
  flex-direction: column;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 178px;
  text-align: center;
  border: 1px dashed var(--el-border-color);
  display: inline-block;
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.el-upload-list) {
  width: 100%;
  display: flex;
  flex-direction: column;

  .el-upload-list__item {
    width: 100%;
    padding: 3px 50px;
  }
}

.row {
  .row-title {
    font-size: 14px;
    font-weight: bold;
    color: #0a1431;
    line-height: 20px;
    padding: 8px 0;
  }
}

.upload-area {
  background: #fafafa;
  border-radius: 4px;

  .upload-tips {
    font-size: 12px;
    font-weight: 400;
    color: #9da1ad;
    line-height: 17px;
    text-align: center;
    padding: 4px 0;
  }
}
</style>
